<template>
  <div>
    <!-- 面包屑导航组见 -->
    <MBX text="用户管理" text1="用户列表"></MBX>
    <!-- 卡片组件 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryData.query"
            clearable
            @clear="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="setData"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="tianJia">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格组件 -->
      <el-table :data="UsersList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="zhuangTai(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip
              effect="dark"
              content="修改"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="xiuGai(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 设置按钮 -->
            <el-tooltip
              effect="dark"
              content="设置"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加用户对话框开始 -->
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="50%"
        @close="addFormClose"
      >
        <!-- 输入框 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="queDing">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加用户对话框结束 -->

      <!-- 编辑用户开始 -->
      <el-dialog title="编辑用户" :visible.sync="addDialogVisible" width="50%">
        <!-- 输入框 -->
        <el-form
          :model="editdialogVisible"
          :rules="addFormRules"
          ref="editFormRef"
          label-width="70px"
          @close="editFormClose"
        >
          <el-form-item label="用户名">
            <el-input v-model="editdialogVisible.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editdialogVisible.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editdialogVisible.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户结束 -->

      <!-- 设置用户对话框开始 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRoleDialogVisible"
        width="50%"
        @close="setRoleDialogClosed"
      >
        <div>
          <p>当前的用户:{{ userInfo.username }}</p>
          <p>当前的角色:{{ userInfo.role_name }}</p>
          <p>
            分配新角色:
            <el-select v-model="selectedRoleID" clearable placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="seveRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 设置用户对话框结束 -->
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 邮箱验证自定义规则
    const checkEmail = (rule, value, calback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/g
      if (regEmail.test(value)) {
        return calback()
      } else {
        calback(new Error('请输入正确的邮箱'))
      }
    }
    // 手机又自定义规则
    const checkMobile = (rule, value, calback) => {
      const regMobile = /^1[3-9]\d{9}$/g
      if (regMobile.test(value)) {
        return calback()
      } else {
        calback(new Error('请输入正确的手机号'))
      }
    }
    return {
      UsersList: [], // 获取到的数据
      total: 0, // 总的数据条数
      queryData: {
        query: '',
        // 当前页码
        pagenum: 1,
        // 每页显示条数
        pagesize: 2
        // 对话框默认隐藏
      },
            // 编辑用户框默认隐藏
      addDialogVisible: false,
      dialogVisible: false, // 对话框默认隐藏
      // 表单的数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },

      // 用户获取的修改数据
      editdialogVisible: {},
      // 分配权限窗口
      setRoleDialogVisible: false,
      // 分配角色的属性
      userInfo: {},
      // 所以角色的列表
      rolesList: [],
      // 已经选中角色的id
      selectedRoleID: ''
    }
  },
  created() {
    this.getUsersList()
  },
  methods: {
    // 获取请求数据
    async getUsersList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryData
      })
      if (res.meta.status !== 200) return this.$message.error('数据请求失败')
      this.UsersList = res.data.users
      this.total = res.data.total
    },
    // 页面显示多少条数据
    handleSizeChange(newSize) {
      this.queryData.pagesize = newSize
      this.getUsersList()
    },
    // 跳转第几页
    handleCurrentChange(newPage) {
      this.queryData.pagenum = newPage
      this.getUsersList()
    },
    // 用户状态修改
    async zhuangTai(scope) {
      const { data: res } = await this.$http.put(
        `users/${scope.id}/state/${scope.mg_state}`
      )
      if (res.meta.status !== 200) {
        scope.mg_state = !scope.mg_state
        return this.$message.error('数据请求失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 用户输入点击搜索的时候发送请求
    setData() {
      this.getUsersList()
    },
    // 添加用户
    tianJia() {
      this.dialogVisible = true
    },
    // 关闭提示框添加用户重置表单
    addFormClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 修改用户窗口关闭重置数据
    editFormClose() {
      this.$refs.editFormRef.resetFields()
    },

    // 确定按钮新增用户
    queDing() {
      this.$refs.addFormRef.validate(async val => {
        // 如果val为真发送请求
        if (val) {
          const { data: res } = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201) {
            return this.$message.error('用户创建失败')
          }
          this.$message.success('用户创建成功')
          this.dialogVisible = false
          // 从新渲染页面
          this.getUsersList()
        }
      })
    },
    // 编辑用户显示与隐藏
    xiuGai(row) {
      this.editdialogVisible = row
      this.addDialogVisible = true
    },
    // 确定修改用户
    editUser() {
      this.$refs.editFormRef.validate(async val => {
        // 如果val为真发送请求
        if (val) {
          const { data: res } = await this.$http.put(
            'users/' + this.editdialogVisible.id,
            this.editdialogVisible
          )
          console.log(res)
          if (res.meta.status !== 200) {
            return this.$message.error('用户编辑失败')
          }
          this.$message.success('用户编辑成功')
          this.addDialogVisible = false
          // 从新渲染页面
          this.getUsersList()
        }
      })
    },
    // 删除当前用户信息
    async removeUser(id) {
      // console.log(id)
      const res = await this.$prompt(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (res !== 'confirm') return this.$message.info('已取消删除')
      // 调用接口删除用户
      const { data: result } = await this.$http.delete('users/' + id)
      // 判断装状态值是不是200 不是就返回失败信息
      if (result.meta.status !== 200) return this.$message.error('用户删除失败')
      // 状态值是200就返回成功信息
      this.$message.success('用户删除成功')
      // 如果当前的页码不是第1也就开始处理
      if (this.queryData.pagenum !== 1) {
        // 如果当前页数据只显示1条了
        if (this.UsersList.length === 1) {
          // 当前的页面就前去1
          this.queryData.pagenum -= 1
        }
      }
      // 并重新渲染页面
      this.getUsersList()
    },
    // 展示分配角色的对话框
    async setRole(userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 点击确定更改角色
    async seveRoleInfo() {
      console.log(this.selectedRoleID)
      if (!this.selectedRoleID) {
        return this.$message.error('请选择分配的角色')
      }
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleID
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.$message.success('分配角色成功')
      // 关闭弹窗
      this.setRoleDialogVisible = false
      // 重新渲染页面
      this.getUsersList()
    },
    // 监听分配角色对话框关闭清空
    setRoleDialogClosed() {
      this.userInfo = {}
      this.selectedRoleID = ''
    }
  }
}
</script>

<style></style>
